import collections


class Solution(object):
    def findAllRecipes(self, recipes, ingredients, supplies):
        r = {r: index for index, r in enumerate(recipes)}
        s = set(supplies)
        d = collections.defaultdict(int)
        e = collections.defaultdict(set)
        for index, food in enumerate(recipes):
            for ori in ingredients[index]:
                if ori in r:
                    d[food] += 1
                    e[ori].add(food)
        now = set()
        ans = []
        for food in r:
            if not d[food]:
                now.add(food)
        while now:
            next_set = set()
            for food in now:
                flag = True
                for ori in ingredients[r[food]]:
                    if ori not in r and ori not in s:
                        flag = False
                        break
                if flag:
                    ans.append(food)
                    for next_food in e[food]:
                        d[next_food] -= 1
                        if d[next_food] == 0:
                            next_set.add(next_food)
            now = next_set
        return ans


data = Solution()
recipes = ["bread", "sandwich", "burger"]
ingredients = [["yeast", "flour"], ["bread", "meat"], ["sandwich", "meat", "bread"]]
supplies = ["yeast", "flour", "meat"]
print(data.findAllRecipes(recipes, ingredients, supplies))
